var EventProxy = require('eventproxy');
var fs = require('fs');
var logger = require('../service/Logger');
var Faction = require('../proxy').Faction;
var Activity = require('../proxy').Activity;
var User = require('../proxy').User;
var FactionMember = require('../proxy').FactionMember;
var redisManager = require('../proxy').RedisManager;
var LogRecord = require('../proxy').LogRecord;
var dateUtil = require('../utils/DateUtil');
var config = require('../config').config;


exports.myFactions = function(req, res, next){
    var me = req.params.currentUser;
    User.getUserById(me.id, function(err, user){
        if(err){
            logger.error(err.message);
            return res.render('others/error', {error: err});
        }
        var factions = user.factions,
            len = factions.length;
        var ep = new EventProxy();
            ep.bind('error', function(err){
                logger.error(err);
                return res.render('others/error', {error: err});
            });
        ep.after('factions', len, function(factions){
            var factionArr = [];
            factions.forEach(function(faction){
                if(faction)
                    factionArr.push(faction);
            })
            res.render('faction/faction_list', {factions: factionArr, user: me})
        });
        for(var i=0; i<len; i++){
            Faction.findById(factions[i].id, function(err, faction){
                if(err) return ep.emit('error', err);
                if(faction.isDelete){
                    ep.emit('factions', null);
                }else{
                    ep.emit('factions', faction);
                }

            })
        }

    })
}

exports.newFaction = function(req, res, next){
    var me = req.params.currentUser;
    res.render('faction/new_faction', {faction:null, creator: me});
}

exports.updateFaction = function(req, res, next){
    var me = req.params.currentUser;
    var id = req.params.id;
    Faction.findById(id, function(err, faction){
        res.render('faction/new_faction', {faction: faction, user: me, creator: faction.creator});
    })
}

exports.verifyAccess = function(req, res, next){
    var me = req.params.currentUser;
    //TODO: fix: redis 得到
    FactionMember.getFactionMembersByUserId(me.id, function(err, fm){
        if(fm){
            next();
        }else{
            return res.render('others/no_access', {msg:''})
        }
    });
}

exports.faction = function(req, res, next){
    var me = req.params.currentUser;
    var id = req.params.id;
    var ep = new EventProxy();
    ep.bind('error', function(err){
        if(err)
            logger.error(err.message);
        ep.unbind();
        return res.render('others/error', {error: err});
    });
    ep.all('faction', 'acts', 'factionMember', function(faction, acts, fm){
        console.log(fm)
        return res.render('faction/faction',
            {   faction:faction,
                acts: acts,
                user: me,
                id: id,
                factionMember: fm,
                dateUtil: dateUtil})
    })
    Faction.findById(id, function(err, faction){
        if(err) ep.emit('error', err);
        ep.emit('faction', faction);
    })
    Activity.pageFactionActs(id, 1, 5, function(err, acts){
        if(err) ep.emit('error', err);
        ep.emit('acts', acts);
    })
    FactionMember.getFmByUserAndFactionId(me.id, id, function(err, fm){
        if(err) ep.emit('error', err);
        ep.emit('factionMember', fm);
    })
}

exports.fetchFactionActs = function(req, res, next){
    var me = req.params.currentUser,
        factionId = req.params.factionId,
        pageNo = parseInt(req.params.pageNo) || 2,
        pageSize = 5;
    Activity.pageFactionActs(factionId, pageNo, pageSize, function(err, acts){
        if(err){logger.error(err);return res.send({error:err.message})}
        res.send({acts: acts, pageNo: pageNo+1, pageSize: pageSize});
    })
}

exports.information = function(req, res, next){
    var me = req.params.currentUser;
    var id = req.params.id,
        from = req.params.from;
    var ep = new EventProxy();
    ep.bind('error', function(err){
        if(err)
            logger.error(err.message);
        ep.unbind();
        res.render('others/error', {error: err});
    })
    ep.all('faction', 'user', 'card', function(faction, user, card){
        me.card = card;
        res.render('faction/faction_info',
            {fromUser:user, faction:faction, user: me})
    })
    User.getUserById(me.id, function(err, user){
        if(err) return ep.emit('error', err);
        ep.emit('card', user.card);
    })
    User.getUserById(from, function(err, user){
        if(err) return ep.emit('error', err);
        ep.emit('user', user);
    })
    Faction.findById(id, function(err, faction){
        if(err) return ep.emit('error', err);
        ep.emit('faction', faction);
    })
}

exports.joinFaction = function(req, res, next){
    var me = req.params.currentUser,
        factionId = req.body.factionId,
        from = req.body.from;
        me.from = from;
    var ep = new EventProxy();
        ep.all('join', 'user', function(joindata, user){
            joindata.hasinfo = true;
            var card = user.card;
            if(!card.business || !card.company || !card.product){
                joindata.hasinfo = false;
            }
            //log
            _saveFactionLog(me, from, factionId);
            res.send(joindata);
        })
        ep.bind('error', function(err){
            logger.error(err.message);
            ep.unbind();
            return res.send({error: err});
        })
    Faction.addUser2Faction(me, factionId, function(err, data){
        if(err) ep.emit('error', err);
        ep.emit('join', data);
    });
    User.getUserById(me.id, function(err, user){
        if(err) ep.emit('error', err);
        ep.emit('user', user);
    });
}

function _saveFactionLog(me, from, factionId){
    if(me.id === from){
        var content = '有新伙伴: ['+me.name+'] 加入圈子,快去认识一下吧~';
        LogRecord.saveLog('FACTION', factionId, content, null, function(err,log){})
    }else{

    }
    redisManager.getUserById(from, function(err, user){
        var content = '['+user.name+'] 邀请了新伙伴: ['+me.name+'] 加入圈子,快去认识一下吧~';
        LogRecord.saveLog('FACTION', factionId, content, null, function(err,log){})
    })
}

exports.factionLog = function(req, res, next){
    var me = req.params.currentUser,
        factionId = req.params.id;
    res.render('faction/faction_log', {user: me, factionId: factionId});
}

exports.fetchFactionLogs = function(req, res, next){
    var me = req.params.currentUser,
        factionId = req.params.id,
        pageNo = parseInt(req.params.pageNo) || 1,
        pageSize = 10;
    LogRecord.pageLogs('FACTION', factionId, pageNo, pageSize, function(err, logs){
        if(err){
            return res.send({error: err});
        }
        res.send({logs: logs, pageNo: pageNo+1, pageSize: pageSize});
    })
}


exports.members = function(req, res, next){
    var me = req.params.currentUser,
        factionId = req.params.id,
        pageNo = req.params.pageNo?parseInt(req.params.pageNo) : 1;
        pageSize = 10;
    FactionMember.pageMembersByFaction(factionId, pageNo, pageSize,
        function(err, members){
            if(err){logger.error(err);return res.send({error: err.stack});}
            var ep = new EventProxy();
                ep.after('member', members.length, function(list){
                    res.send({members: list, pageNo: pageNo+1});
                })
            for(var i in members){
                var member = members[i].member,
                    permission = members[i].permission;
                if(permission){
                    member = {
                        id: member.id,
                        name: member.name,
                        position: permission.showPosition?member.position:'',
                        company: permission.showCompany?member.company:''
                    }
                }
                ep.emit('member', member);
            }
    });
}

exports.topics = function(req, res, next){
    //TODO:

}

exports.acts = function(req, res, next){
    //TODO:
}

exports.tick = function(req, res, next){
    var me = req.params.currentUser,
        factionId = req.body.faction,
        targetId = req.body.id;
    Faction.tickAUserfromFaction(factionId, targetId, me.id, function(err, data){
        if(err){logger.error(err);return res.send({error:err.message})}
        res.send(data);
    })
}

exports.privacy = function(req, res, next){
    var me = req.params.currentUser,
        factionId = req.params.factionId;
    var ep = new EventProxy();
    ep.bind('error', function(err){
        logger.error(err.stack);
        ep.unbind();
    })
    ep.all('fm', 'user', function(fm, user){
        console.log(fm.permission)
        res.render('faction/privacy', {
            faction:fm.faction,
            permission: fm.permission,
            user:user,
            card: user.card});
    })
    User.getUserById(me.id, function(err, user){
        if(err) ep.emit('error', err);
        ep.emit('user', user);
    })
    FactionMember.getFactionMembersByUserIdAndFactionId(me.id, factionId, function(err, fm){
        if(err) ep.emit('error', err);
        if(!fm.permission || !fm.permission.hasOwnProperty('showProduct')){
            console.log('初始化权限')
            fm.permission = {
                showCard: false,
                showMobile: false,
                showCompany: true,
                showBusiness: true,
                showPosition: true,
                showProduct: true,
                showEmail: true
            }
            fm.save(function(err, fm){
                return ep.emit('fm', fm);
            })
        }else{
            return ep.emit('fm', fm);
        }
    })
}

exports.save = function(req, res, next){
    var me = req.params.currentUser;
    var name = req.body.name,
        description = req.body.description,
        tags = req.body.tags.split(',');
    var id = req.body.factionId;
    console.log(tags)
    if(id){
        Faction.updateFaction(id, {
            name: name,
            description: description,
            tags: tags
        }, function(err, resp){
            if(err) return res.render('others/error', {error: err})
            _uploadFactionLogo(req.files.logofile, id+'.jpg');
            res.redirect('/faction/'+id);
        })
    }else{
        Faction.newAndSave(me, name, description, tags, null, function(err, faction){
            if(err){
                logger.error(e.message);
                return res.render('others/error', {error: err})
            }else{
                _uploadFactionLogo(req.files.logofile, faction._id+'.jpg');
                //return res.send({faction: faction});
                res.redirect('/faction/'+faction._id);
            }
        })
    }
}

function _uploadFactionLogo(file, fileName){
    var contentType = file.headers['content-type'];
    if(file.originalFilename !== '' && contentType === 'image/jpeg'){
        var tempPath = file.path
        fs.readFile(tempPath, {}, function(err, buffer){
            fs.writeFile(config.app_root_dir + '/static/img/flogo/'+fileName, buffer, {}, function(err, data){
                console.log('上传圈子logo成功')
            })
        })
    }else{
        console.log('没有圈子logo...')
    }
}

exports.delete = function(req, res, next){
    var me = req.params.currentUser;
    var id = req.body.id;
    Faction.deleteById(me, id, function(err, faction){
        if(err) return res.send({error: err.msg});
        res.send({faction: faction});
    })
}